import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mwm/base/base.dart';
import 'package:flutter_mwm/beans/bean.dart';
import 'package:flutter_mwm/icons/weather_icons.dart';
import 'package:flutter_mwm/impl/http.dart';
import 'package:flutter_mwm/impl/impl.dart';
import 'package:flutter_mwm/ui/city.dart';
import 'package:flutter_mwm/util/util.dart';
import 'package:flutter_mwm/widget/button.dart';
import 'package:flutter_mwm/widget/text.dart';
import 'package:flutter_mwm/widget/widget.dart';

class WeatherHome extends BaseWidget<WeatherHome> {
  final String cityName;

  WeatherHome({this.cityName});

  @override
  State<StatefulWidget> createState() {
    return _StateWeather();
  }
}

class _StateWeather extends StateBase<WeatherHome> implements HttpCallbackImpl {
  var cName = '西安';

  WeatherBean weatherBean;
  var forecastList = List();

  @override
  void initState() {
    super.initState();
    cName = widget.cityName;
    _cityWeather();
  }

  @override
  Widget build(BuildContext context) {
    return PhotoWallpaper(
      context,
      title: '天气',
      appBarActions: <Widget>[_actionView()],
      child: _bodyWidget(),
    );
  }

  /*appBar右侧编辑栏*/
  Widget _actionView() {
    return ButtonText(
      '西安',
      onPressed: _changeCity,
      background: Color(0xFF051728),
      highlightBackground: Color(0xFF051728),
      textColor: Colors.green,
      textSize: 18,
    );
  }

  Widget _bodyWidget() {
    return null == weatherBean
        ? Center(child: CupertinoActivityIndicator())
        :
        ListView(children: <Widget>[
      TextView(
        '${weatherBean.ganmao}',
        textColor: Color(0xFFEE2C2C),
        textSize: 18,
        padding: EdgeInsets.all(8),
        textAlign: TextAlign.left,
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          TextView('${weatherBean.wendu}', textSize: 50, textColor: Colors.white),
          TextView('℃',
              margin: EdgeInsets.only(top: 10),
              textSize: 18,
              textColor: Colors.white),
        ],
      ),
      _weatherList(),
    ]);
  }

  Widget _wind(String high, String low) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        TextView(
          '$high'.replaceAll('高温', '').trim(),
          textColor: Colors.white,
          textSize: 18,
        ),
        TextView(
          ' / ',
          textColor: Colors.blueGrey,
          textSize: 18,
        ),
        TextView(
          '$low'.replaceAll('低温', '').trim(),
          textColor: Colors.blueGrey,
          textSize: 18,
        )
      ],
    );
  }

  Widget _weatherList() {
    return ListView.builder(
      shrinkWrap: true,
      itemBuilder: (context, index) {
        return _childWidget(forecastList[index]);
      },
      itemCount: forecastList.length,
    );
  }

  Widget _childWidget(WeatherForecastBean forecastBean) {
    Color color = Colors.white;
    var date = forecastBean.date;
    var type = forecastBean.type;
    var high = forecastBean.high;
    var low = forecastBean.low;
    return Container(
      padding: EdgeInsets.all(8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          TextView('$date', textColor: color, textSize: 18),
          _weatherIcon(type),
          _wind('$high', '$low'),
        ],
      ),
      decoration: BoxDecoration(
          border: Border(bottom: BorderSide(color: Colors.white10))),
    );
  }

  _weatherIcon(String type) {
    IconData icon;
    if (TextUtils.isEmpty(type)) icon = Weather.sun;
    if (TextUtils.equals("多云", type)) {
      icon = Weather.cloud_sun_inv;
    } else if (TextUtils.equals("晴", type)) {
      icon = Weather.sun;
    } else if (TextUtils.equals("阴", type)) {
      icon = Weather.clouds;
    } else if (type.endsWith("雪")) {
      icon = Weather.snow;
    } else if (type.endsWith("雨")) {
      icon = Weather.rain;
    }

    return Icon(icon, color: Colors.white);
  }

  //------method-------

  _cityWeather() {
    if (TextUtils.isEmpty(cName)) {
      cName = "西安";
    } else {
      cName = TextUtils.endWith(cName, "市")
          ? cName.substring(0, cName.length - "市".length)
          : cName;
    }

    String weatherUrl = "http://wthrcdn.etouch.cn/weather_mini?city=$cName";
    var http = HttpKit.getInstance();
    http.callback(this);
    http.get(url: weatherUrl);
  }

  void _changeCity() {
    Navigator.push(context, MaterialPageRoute(builder: (_) => CityHome()))
        .then((value) {
      if (!TextUtils.isEmpty(value)) {
        setState(() {
          cName = value;
        });
      }
    });
  }

  @override
  void onResult(int what, Object tag, String result) {
    Log.out('weather', tag: result);
    try {
      result = result
          .replaceAll('{"data":', '')
          .replaceAll(',"status":1000,"desc":"OK"}', '');
      WeatherBean tempBean = WeatherBean.json2Bean(result);
      if (null == tempBean) {
        showPromptDialog("数据格式错误或未返回数据！");
        return;
      }
      var tmpList = null == tempBean.forecast ? List() : tempBean.forecast;
      setState(() {
        weatherBean = tempBean;
        forecastList = tmpList;
      });
    } catch (error) {
      onError(what, tag, error.toString());
    }
  }

  @override
  void onError(int what, Object tag, String e) {
    showToast("获取天气数据失败：" + e);
  }
}
